package com.hudsonmq.spring.handler.process;

import com.hudson.codec.domain.RemotingCommand;
import com.hudson.common.enums.MessageTypeEnum;
import com.hudson.core.concurrent.CallBack;
import com.hudsonmq.spring.handler.Process;
import com.hudsonmq.spring.impl.produce.helper.SendCallBack;
import com.hudsonmq.spring.impl.produce.helper.SendMessageSyncHelper;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component
@ConditionalOnProperty(prefix = "hudson",name = "produce-group")
public class ProducerRespHandler implements Process {

    private static final Logger logger = LoggerFactory.getLogger(ProducerRespHandler.class);


    @Override
    public String getType() {
        return MessageTypeEnum.SEND_MESSAGE_RESP.getType();
    }

    @Override
    public RemotingCommand process(ChannelHandlerContext context, RemotingCommand remotingCommand) {
        // todo: 后续添加成功还是失败
        CompletableFuture<Boolean> booleanCompletableFuture = SendMessageSyncHelper.getFuture(remotingCommand.getOpaque());
        if (booleanCompletableFuture != null) {

            booleanCompletableFuture.complete(true);
        }

        SendCallBack sendCallBack = SendMessageSyncHelper.getCallback(remotingCommand.getOpaque());
        CallBack callback = SendMessageSyncHelper.getCallback1(remotingCommand.getOpaque());
        if (callback != null) {
            // todo: 后续添加成功还是失败
            callback.onSuccess();
        }
        if (sendCallBack != null) {
            // todo: 后续添加成功还是失败
            sendCallBack.onSuccess();
        }
        logger.debug("客户端收到服务端消息: {}", remotingCommand);
        return null;
    }
}
